package io.renren.modules.gis_admin.controller;

import io.renren.common.constant.Constant;
import io.renren.common.page.PageData;
import io.renren.common.utils.Result;
import io.renren.modules.gis_admin.dto.MapLayersDTO;
import io.renren.modules.gis_admin.service.MapLayersService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.InputStreamResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/map/api")
@Api(tags = "地图模块基本API")
public class BasicMapApiController {
    @Autowired
    private MapLayersService mapLayersService;

    @Value("${shapefile-path}")
    String shapefilePath;

    @GetMapping("layer")
    @ApiOperation("所有图层信息")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "displayName", value = "图层展示名称", paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "layerName", value = "图层名称", paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "layerType", value = "图层分类", paramType = "query", dataType = "String")
    })
    public Result<List<MapLayersDTO>> page(@ApiIgnore @RequestParam Map<String, Object> params) {
        List<MapLayersDTO> page = mapLayersService.list(params);

        return new Result<List<MapLayersDTO>>().ok(page);
    }

    @GetMapping("shapefile")
    @ApiOperation("获取shapefile")
    public ResponseEntity<InputStreamResource> downloadZip(String fileName) throws IOException {
        // 读取zip文件的路径
        String filePath = shapefilePath+File.separator+fileName+".zip";
        // 创建文件对象
        File file = new File(filePath);
        // 创建文件输入流
        InputStream inputStream = new FileInputStream(file);
        // 创建输入流资源对象
        InputStreamResource resource = new InputStreamResource(inputStream);
        // 设置响应头，让浏览器下载文件
        HttpHeaders headers = new HttpHeaders();
        headers.add("Content-Disposition", "attachment; filename=" +fileName+".zip");
        // 创建响应实体对象
        ResponseEntity<InputStreamResource> response = ResponseEntity.ok()
                .headers(headers)
                .contentLength(file.length())
                .contentType(MediaType.parseMediaType("application/zip"))
                .body(resource);
        return response;
    }
}
